﻿@*
//------------------------------------------------------------------------------
//  此代码版权声明为全文件覆盖，如有原作者特别声明，会在下方手动补充
//  此代码版权（除特别声明外的代码）归作者本人Diego所有
//  源代码使用协议遵循本仓库的开源协议及附加协议
//  Gitee源代码仓库：https://gitee.com/diego2098/ThingsGateway
//  Github源代码仓库：https://github.com/kimdiego2098/ThingsGateway
//  使用文档：https://diego2098.gitee.io/thingsgateway-docs/
//  QQ群：605534569
//------------------------------------------------------------------------------
*@

@page "/tgruntime/hisvalue"
@namespace ThingsGateway.Web.Page
@using System.Linq.Expressions;
@using BlazorComponent;
@using Furion.DataValidation;
@using Mapster;
@using Masa.Blazor.Presets;
@using System.IO;
@using TouchSocket.Core;
@attribute [Authorize]
@inject MasaBlazor MasaBlazor
@attribute [RolePermission]
@inherits CultureComponentBase
@inject UserResoures UserResoures
@layout MainLayout
<AppDataTable @ref="_datatable" TItem="ValueHis" SearchItem="HisPageInput"
              AddItem="object" EditItem="object" ShowSelect=false
              IsMenuOperTemplate=false
              QueryCall="QueryCall"
              FilterHeaders="FilterHeaders" Filters="Filters" ShowDetailButton
                ShowQueryButton>
    <SearchTemplate>

        <MMenu CloseOnContentClick="false" OffsetY Context="menu">
            <ActivatorContent>
                <MTextField Dense Readonly Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " Value="context.StartTime.GetValueOrDefault().Add(JsInitVariables.TimezoneOffset)"
                                    Clearable
                @attributes="menu.Attrs" Outlined Label=@context.Description(x => x.StartTime) />
            </ActivatorContent>
            <ChildContent>
                <AppDateTimePicker ClassString="my-1  mx-2 " @bind-Value="context.StartTime"></AppDateTimePicker>
            </ChildContent>
        </MMenu>

        <MMenu CloseOnContentClick="false" OffsetY Context="menu">
            <ActivatorContent>
                <MTextField Dense Readonly Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " Value="context.EndTime.GetValueOrDefault().Add(JsInitVariables.TimezoneOffset)" Clearable
                @attributes="menu.Attrs" Outlined Label=@context.Description(x => x.EndTime) />
            </ActivatorContent>
            <ChildContent>
                <AppDateTimePicker ClassString="my-1  mx-2 " @bind-Value="context.EndTime"></AppDateTimePicker>
            </ChildContent>
        </MMenu>


        <MTextField Dense Style="max-width:200px;" HideDetails=@("auto") Class="my-1  mx-2 " @bind-Value="context.Name" Clearable
                        Outlined Label=@context.Description(x => x.Name) />


    </SearchTemplate>

    <ItemColTemplate>
        @if (context.Header.Value == nameof(context.Item.Quality))
        {
            <EnableChip Value="context.Item.Quality==192" DisabledLabel=@context.Item.Quality.ToString() EnabledLabel=@context.Item.Quality.ToString()>
            </EnableChip>
        }

        else
        {
            @context.Value

        }

    </ItemColTemplate>

</AppDataTable>


@code {
    [Parameter]
    [SupplyParameterFromQuery]
    public string DeviceName { get; set; }
    [Inject] public JsInitVariables JsInitVariables { get; set; } = default!;

    HisPageInput _searchModel { get; set; } = new();
    private IAppDataTable _datatable;
    ValueHisWorker ValueHisHostService { get; set; }

    protected override async Task OnInitializedAsync()
    {
        ValueHisHostService = ServiceExtension.GetBackgroundService<ValueHisWorker>();
        _searchModel.DeviceName = DeviceName;
        await base.OnInitializedAsync();
    }


    private async Task datatableQuery()
    {
        await _datatable?.QueryClickAsync();
    }


    private void FilterHeaders(List<DataTableHeader<ValueHis>> datas)
    {
        datas.RemoveWhere(it => it.Value == nameof(ValueHis.Id));
        foreach (var item in datas)
        {
            item.Sortable = false;
            item.Filterable = false;
            item.Divider = false;
            item.Align = DataTableHeaderAlign.Start;
            item.CellClass = " table-minwidth ";
            switch (item.Value)
            {
                case nameof(ValueHis.Name):
                    item.Sortable = true;
                    break;

                case nameof(ValueHis.Quality):
                    item.Sortable = true;
                    break;
                case nameof(ValueHis.CollectTime):
                    item.Sortable = true;
                    break;
            }
        }
    }

    private void Filters(List<Filters> datas)
    {
        foreach (var item in datas)
        {

        }
    }


    private async Task<SqlSugarPagedList<ValueHis>> QueryCall(HisPageInput input)
    {
        var result = await ValueHisHostService.GetHisDbAsync();
        if (result.IsSuccess)
        {
            try
            {
                return await Task.Run(async () =>
                {
                    var data = await result.Content.CopyNew().Queryable<ValueHis>()
               .WhereIF(!input.Name.IsNullOrEmpty(), a => a.Name.Contains(input.Name))
               .WhereIF(input.StartTime != null, a => a.CollectTime >= input.StartTime)
               .WhereIF(input.EndTime != null, a => a.CollectTime <= input.EndTime)
                   .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"{input.SortField} {input.SortOrder}")
               .ToPagedListAsync(input.Current, input.Size);
                    return data;
                });
            }
            catch (Exception ex)
            {
                await InvokeAsync(async () => await PopupService.EnqueueSnackbarAsync("查询失败，请检查网络连接", AlertTypes.Warning));
                return new() { Current = 1, Size = 10, Pages = 0, Records = new List<ValueHis>(), Total = 0 };
            }

        }
        else
        {
            await InvokeAsync(async () => await PopupService.EnqueueSnackbarAsync(result.Message, AlertTypes.Warning));
            return new() { Current = 1, Size = 10, Pages = 0, Records = new List<ValueHis>(), Total = 0 };
        }

    }
}
